package org.fenixsoft.jvm.chapter7.my;

import org.fenixsoft.jvm.util.Fileutil;

/**
 * 运行结果：Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
 *
 * 无论是系统的AppClassLoader， 还是自定义的ClassLoader都无法加载java.lang包下的class。
 * java.lang下的class只能由BootstrapCLassloader加载
 */

public class MyStringTest {

    public static final String MYSTRING_PATH = "E:\\Java\\idea project\\UnderstandingTheJvm3\\src\\org\\fenixsoft\\jvm\\chapter7\\my\\MyString.class";

    public static void main(String[] args) throws Exception {
        MyStringClassLoader classLoader = new MyStringClassLoader(MYSTRING_PATH);
        classLoader.loadClass("java.lang.MyString");
    }

    static class MyStringClassLoader extends ClassLoader {
        private String classFilePath;

        public MyStringClassLoader(String classFilePath) {
            this.classFilePath = classFilePath;
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            try {
                byte[] bytes = Fileutil.getFileByte2(classFilePath);
                if (bytes == null) {
                    return super.loadClass(name);
                }
                return defineClass(name, bytes, 0, bytes.length);
            } catch (Exception e) {
                throw e;
            }
        }
    }
}
